package NIO;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author:谢君臣
 * @Date:2021/7/26-15:33
 * @version:1.0
 * @function:
 */
public class Selector_test {

    /*
       服务端
     */

    @Test
    public void test() throws Exception{
        //获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 切换非阻塞模式
        serverSocketChannel.configureBlocking(false);
        // 绑定连接
        serverSocketChannel.bind(new InetSocketAddress(8888));
        // 创建selector
        Selector selector = Selector.open();
        // 将通道注册到选择器上，并指定监听事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 轮询获取选择器上已经就绪的事件
        while (selector.select()>0){
            System.out.println("开始轮询");
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()){
                    SocketChannel accept = serverSocketChannel.accept();
                    accept.configureBlocking(false);
                    // 将通道注册到选择器上
                    accept.register(selector,SelectionKey.OP_READ);
                }else if (selectionKey.isReadable()){
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len = 0  ;
                    while ((len = channel.read(buffer))!=-1){
                        // 切换可读模式
                        buffer.flip();
                        System.out.println(new String(buffer.array(), 0, len));
                        buffer.clear();
                    }
                }
            }
            iterator.remove();
        }
        // 最终关闭选择器
        selector.close();
        // 关闭通道
        serverSocketChannel.close();
    }
    @Test
    public void test1(){

    }
}
